<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { getEzvizToken } from '@/api/auth'
import { getHomeChannelList, getCheckList } from '@/api/h3yun'
import type { ChannelInfo } from '@/api/h3yun'
import VideoItem from './VideoItem.vue'
import SensorData from './SensorData.vue'
import EZUIKit from "ezuikit-js"

// 声明萤石云SDK类型
declare global {
  interface Window {
    EZUIKit: any;
  }
}

// 定义组件属性
interface VideoEleItem {
  ItemVisible: boolean;
  VisibleType: string;
  VisibleList: string;
  ItemValue: string;
  ItemName: string;
}

const props = defineProps({
  // 视频区域标题
  title: {
    type: String,
    default: '实时视频监控'
  },
  // 处理WebSocket消息的回调函数
  handleWsMessage: {
    type: Function,
    default: () => { }
  },
  // 视频配置元素列表
  videoEleList: {
    type: Array as () => VideoEleItem[],
    default: () => []
  },
  // 视频配置元素列表
  powerCode: {
    type: String,
    default: ''
  },
  // 区域编码
  areaCode: {
    type: String,
    default: ''
  }
})

// 定义事件
const emit = defineEmits(['setFullScreen'])

// 视频播放模式
type VideoMode = 1 | 2 | 4 | 9;

// 定义监控点总数和每页显示数量
const ROTATION_INTERVAL = 1 * 60 * 1000; // 1分钟切换一次

// 当前视频模式：1/2/4/9格子
const currentMode = ref<VideoMode>(4); // 默认为4分屏

// 每页显示数量，随模式变化
const ITEM_PAGE_CAMERAS = computed(() => currentMode.value);

// 轮播定时器类型
type Timer = ReturnType<typeof setInterval>;
let rotationTimer: Timer | null = null;

// 萤石云token
const accessToken = ref('')

// 萤石云配置
const ezConfig = ref({
  accessToken: ''
})

// 定义数据项映射关系
const visibleListMap: Record<string, string> = {
  '实时数据': 'Rtd',
  '最大值': 'Max',
  '最小值': 'Min',
  '平均值': 'Avg',
  '累计值': 'Cou'
}

// 视频网格数据 - 所有监控点
const allCameras = ref<{
  name: string;
  loading: boolean;
  error: boolean;
  url: string;
  player: any;
  SensorDeviceMN?: string; // 添加传感器MN关联
  adcode?: string;
  SensorData?: any; // 添加监控点对应的传感器事件数据
  SensorBy?: string; // 添加监控点对应的传感器类型
  OrgId?: string;
}[]>([])

// 当前过滤后的监控点列表
const filteredCamerasList = ref<typeof allCameras.value>([])

// 当前显示的视频网格
const videoGrids = ref<typeof allCameras.value>([])

// 当前页码
const currentPage = ref(0)

watch(() => props.areaCode, () => {
  fetchChannelList(true)
})

// 定义事件
defineExpose({
  // 对外暴露刷新方法
  refreshCameras: (isRefresh = false) => {
    fetchChannelList(isRefresh)
  },
  // 对外暴露处理传感器数据方法
  processSensorData: (data: any) => {
    processSensorData(data)
  },
  filterCurrentRegionList: (data) => filterCurrentRegionList(data)
})

const filterCurrentRegionList = (adcode) => {
  // 停止所有播放器
  stopAllPlayers();

  // 如果选择中国，或者adcode为空/null/undefined，则展示所有监控点
  const isShowAll = !adcode || adcode === '100000' || adcode === '0'; // 假设100000是中国的adcode

  // 根据条件筛选摄像头列表
  let filtered = [];

  if (isShowAll) {
    // 全国范围，显示所有监控点
    filtered = [...allCameras.value];
  } else {
    // 检查adcode是否为UUID格式（简单判断：包含连字符且长度大于20）
    const adcodeStr = String(adcode);
    const isUUID = adcodeStr.includes('-') && adcodeStr.length > 20;

    if (isUUID) {
      // 如果是UUID格式，则使用OrgId字段进行精确匹配
      console.log(`检测到UUID格式的组织ID: ${adcodeStr}，使用OrgId过滤`);
      filtered = allCameras.value.filter(camera =>
        camera.OrgId === adcodeStr
      );
    } else {
      // 判断是否为省级编码（以00结尾的4位或以0000结尾的6位）
      const isProvinceLevel = adcodeStr.endsWith('0000');
      // 判断是否为市级编码（以00结尾但不是省级）
      const isCityLevel = adcodeStr.endsWith('00') && !isProvinceLevel;

      if (isProvinceLevel) {
        // 省级编码，截取前2位，匹配所有以该前缀开头的adcode
        const provincePrefix = adcodeStr.substring(0, 2);
        filtered = allCameras.value.filter(camera =>
          camera.adcode && String(camera.adcode).startsWith(provincePrefix)
        );
      } else if (isCityLevel) {
        // 市级编码，截取前4位，匹配所有以该前缀开头的adcode
        const cityPrefix = adcodeStr.substring(0, 4);
        filtered = allCameras.value.filter(camera =>
          camera.adcode && String(camera.adcode).startsWith(cityPrefix)
        );
      } else {
        // 区县级编码，完全匹配
        filtered = allCameras.value.filter(camera =>
          camera.adcode === adcodeStr
        );
      }
    }
  }

  // 更新过滤后的监控点列表
  filteredCamerasList.value = filtered;

  // 重置到第一页
  const pageIndex = 0;
  currentPage.value = pageIndex;

  // 计算分页
  const totalCameras = filteredCamerasList.value.length;
  const startIndex = pageIndex * ITEM_PAGE_CAMERAS.value;
  const endIndex = Math.min(startIndex + ITEM_PAGE_CAMERAS.value, totalCameras);

  // 更新视频网格
  videoGrids.value = filteredCamerasList.value.slice(startIndex, endIndex);

  // 使用nextTick确保DOM已更新后再初始化播放器
  nextTick(() => {
    // 延迟一点时间确保DOM已完全渲染
    setTimeout(() => {
      console.log(`根据地区过滤(${adcode})后初始化播放器，共${totalCameras}个设备`);

      // 此时布局已完成，初始化播放器
      initCurrentPagePlayers();

      // 如果有多个可轮播的页面，启动轮播
      if (totalCameras > ITEM_PAGE_CAMERAS.value) {
        startRotation();
      }
    }, 200);
  });

  return {
    total: totalCameras,
    pageSize: ITEM_PAGE_CAMERAS.value,
    totalPages: Math.ceil(totalCameras / ITEM_PAGE_CAMERAS.value),
    currentPage: pageIndex + 1
  };
}

// 获取萤石云Token
const fetchEzvizToken = async () => {
  try {
    const res = await getEzvizToken()
    if (res && res.code === '0' && res.data) {
      accessToken.value = res.data
      ezConfig.value.accessToken = res.data
    } else {
      console.error('获取萤石云Token失败:', res)
    }
  } catch (error) {
    console.error('获取萤石云Token异常:', error)
  }
}

// 获取检查列表
const checkList = ref<any[]>([])
const fetchCheckList = async () => {
  const res = await getCheckList()
  if (res && res.code === '0' && res.data) {
    checkList.value = res.data
  }
}

const getSensorDataFromCheckList = (objectId: string) => {
  /*
  返回格式：
  [
    {
      "key": "化学需氧量",
      "label": "化学需氧量",
      "value": undefined
    }
  ]
  */
  const checkItem = checkList.value.find(item => item.F0000009 === objectId) // F0000009为监控点ID
  //D001729smhwnesqbbuur7glx8rbq D001729smhwnesqbbuur7glx8rbq.Name D001729smhwnesqbbuur7glx8rbq.F0000014
  if (!checkItem) return []
  const sensorData = checkItem.D001729smhwnesqbbuur7glx8rbq.map(item => {
    return {
      key: item.Name,
      label: item.Name,
      value: item.F0000014
    }
  })
  return sensorData
}

// 获取监控点列表
const listLoading = ref(true)
const fetchChannelList = async (isRefresh = false) => {
  try {
    // 如果是刷新操作，先停止所有播放器
    if (isRefresh) {
      stopAllPlayers();
    }
    listLoading.value = true
    const res: any = await getHomeChannelList(props.areaCode)
    listLoading.value = false
    if (res && res.code === '0' && res.data) {
      // 将接口返回的监控点数据转换为页面需要的格式
      let onlineCameras = res.data.sort((a, b) => a.sortVal - b.sortVal)
      allCameras.value = onlineCameras.map((channel: ChannelInfo) => ({
        name: channel.ChannelName,
        loading: true,
        error: false,
        // 组装播放地址: ezopen://open.ys7.com/设备序列号/通道号.hd.live
        url: `ezopen://open.ys7.com/${channel.DeviceSerial}/${channel.ChannelNo}.hd.live`,
        player: null,
        // 添加传感器MN关联
        SensorDeviceMN: channel.SensorDeviceMN,
        adcode: channel.adcode,
        OrgId: channel.OrgId,
        SensorData: getSensorDataFromCheckList(channel.ObjectId)
      }))

      console.log('默认采送检列表赋值完成:', [...allCameras.value])

      // 初始化过滤列表为所有监控点
      filteredCamerasList.value = [...allCameras.value];

      // 计算总页数并初始化第一页
      const totalCameras = allCameras.value.length
      if (totalCameras > 0) {
        // 重置到第一页
        const pageIndex = 0;
        currentPage.value = pageIndex;
        const startIndex = pageIndex * ITEM_PAGE_CAMERAS.value;
        const endIndex = Math.min(startIndex + ITEM_PAGE_CAMERAS.value, totalCameras);
        videoGrids.value = allCameras.value.slice(startIndex, endIndex);

        // 如果是刷新操作，等DOM更新后重新初始化播放器
        if (isRefresh) {
          nextTick(() => {
            setTimeout(() => {
              console.log('刷新监控点列表，重新初始化播放器');
              initCurrentPagePlayers();

              // 如果有多个可轮播的页面，重新启动轮播
              if (filteredCamerasList.value.length > ITEM_PAGE_CAMERAS.value) {
                startRotation();
              }
            }, 200);
          });
        }

        return true;
      } else {
        videoGrids.value = []
      }
      return false;
    } else {
      console.error('获取监控点列表失败:', res)
      return false;
    }
  } catch (error) {
    listLoading.value = false
    console.error('获取监控点列表异常:', error)
    return false;
  }
}

// 停止所有播放器
const stopAllPlayers = () => {
  allCameras.value.forEach(camera => {
    if (camera.player) {
      try {
        camera.player.stop();
        camera.player = null;
      } catch (error) {
        console.error('停止播放器失败:', error);
      }
    }
  });
}

// 切换到指定页面
const switchToPage = (pageIndex: number) => {
  // 停止所有播放器
  stopAllPlayers();

  const totalCameras = filteredCamerasList.value.length;
  const totalPages = Math.ceil(totalCameras / ITEM_PAGE_CAMERAS.value);

  // 验证页面索引是否有效
  if (totalPages === 0) {
    console.warn('没有可用的监控点');
    return;
  }

  // 确保页面索引在有效范围内
  pageIndex = Math.max(0, Math.min(pageIndex, totalPages - 1));

  // 更新当前页码
  currentPage.value = pageIndex;

  // 计算页面显示的监控点范围
  const startIndex = pageIndex * ITEM_PAGE_CAMERAS.value;
  const endIndex = Math.min(startIndex + ITEM_PAGE_CAMERAS.value, totalCameras);

  // 更新视频网格
  videoGrids.value = filteredCamerasList.value.slice(startIndex, endIndex);

  // 使用nextTick确保DOM已更新后再初始化播放器
  nextTick(() => {
    // 延迟一点时间确保DOM已完全渲染
    setTimeout(() => {
      console.log(`切换到第${pageIndex + 1}页，初始化播放器`);

      // 此时布局已完成，初始化播放器
      initCurrentPagePlayers();
    }, 200);
  });
}

// 初始化当前页面的播放器
const initCurrentPagePlayers = () => {
  const startIndex = currentPage.value * ITEM_PAGE_CAMERAS.value;

  // 逐个初始化播放器，避免同时初始化多个播放器导致的问题
  const initPlayer = (index: number) => {
    if (index >= videoGrids.value.length) return;

    const camera = videoGrids.value[index];
    const globalIndex = startIndex + index;

    try {
      camera.loading = true;
      camera.error = false;

      // 检查DOM元素是否存在
      const videoElement = document.getElementById(`video_dom_${index}`);
      if (!videoElement) {
        console.error(`视频DOM元素 video_dom_${index} 不存在`);
        camera.loading = false;
        camera.error = true;

        // 继续初始化下一个播放器
        setTimeout(() => initPlayer(index + 1), 100);
        return;
      }

      // 创建播放器实例
      const player = new EZUIKit.EZUIKitPlayer({
        id: `video_dom_${index}`,
        url: camera.url,
        audio: false, // 关闭音频
        template: "security",
        plugin: ["talk"],
        width: playerSize.value.width,
        height: playerSize.value.height,
        accessToken: ezConfig.value.accessToken,
        streamInfoCBType: 1,
        handleSuccess: (data) => {
          console.log("**handleSuccess ok**", data)
          camera.loading = false;
        }
      });

      // 更新播放器引用
      allCameras.value[globalIndex].player = player;

      player.handleSuccess = () => {
        // camera.loading = false;
      }

      // 设置错误处理
      player.handleError = () => {
        camera.loading = false;
        camera.error = true;
      };

      // 延迟初始化下一个播放器
      setTimeout(() => initPlayer(index + 1), 200);

    } catch (error) {
      console.error(`初始化视频 ${globalIndex + 1} 失败:`, error);
      camera.loading = false;
      camera.error = true;

      // 出错也继续初始化下一个
      setTimeout(() => initPlayer(index + 1), 200);
    }
  };

  // 开始初始化第一个播放器
  initPlayer(0);
}

const isFullScreenStatus = ref(false)
const fullInfo: any = ref({})

watch(isFullScreenStatus, (newVal) => {
  emit('setFullScreen', newVal)
})

const handleDoubleClick = (item: any) => {
  const player = item.player
  if (!player) {
    console.error('播放器实例不存在，无法进入全屏模式')
    return
  }

  isFullScreenStatus.value = !isFullScreenStatus.value
  fullInfo.value = { ...item }

  try {
    // 检测浏览器类型
    const isEdge = navigator.userAgent.indexOf("Edg") !== -1;
    console.log('当前浏览器:', navigator.userAgent, '是否Edge:', isEdge);

    if (true) {
      // 获取视频容器DOM元素ID
      const videoContainerId = player.id; // 通常是 video_dom_0 等
      const videoContainer = document.getElementById(videoContainerId);

      if (videoContainer) {
        console.log('Edge浏览器使用CSS方式实现全屏', isFullScreenStatus.value);

        // 创建一个标记，记录当前是否处于全屏状态
        const isFullscreen = videoContainer.getAttribute('data-fullscreen') === 'true';

        if (!isFullscreen) {
          // 保存原始样式以便恢复
          const originalStyles = {
            position: videoContainer.style.position,
            width: videoContainer.style.width,
            height: videoContainer.style.height,
            top: videoContainer.style.top,
            left: videoContainer.style.left,
            zIndex: videoContainer.style.zIndex
          };

          // 存储原始样式
          videoContainer.setAttribute('data-original-styles', JSON.stringify(originalStyles));

          // 设置全屏样式
          videoContainer.style.position = 'fixed';
          videoContainer.style.width = '100%';
          videoContainer.style.height = '100%';
          videoContainer.style.top = '0';
          videoContainer.style.left = '0';
          videoContainer.style.zIndex = '9999';

          // 标记为全屏状态
          videoContainer.setAttribute('data-fullscreen', 'true');

          // 添加ESC键退出全屏的事件监听
          document.addEventListener('keydown', handleEscKeyExit);
        } else {
          // 恢复原始样式
          exitCustomFullscreen(videoContainer);
        }
      } else {
        console.error('无法找到视频容器元素:', videoContainerId);
        // 尝试使用萤石云的方式
        player.fullScreen();
      }
    } else {
      // 其他浏览器使用萤石云SDK的全屏方法
      player.fullScreen();
    }
  } catch (error) {
    console.error('进入全屏模式失败:', error);
    // 出错时尝试使用标准全屏API作为备选方案
    try {
      const container = document.querySelector('#' + player.id);
      if (container) {
        // 使用any类型绕过TypeScript检查
        const containerEl = container as any;

        if (containerEl.requestFullscreen) {
          containerEl.requestFullscreen();
        } else if (containerEl.webkitRequestFullscreen) {
          containerEl.webkitRequestFullscreen();
        } else if (containerEl.mozRequestFullScreen) {
          containerEl.mozRequestFullScreen();
        } else if (containerEl.msRequestFullscreen) {
          containerEl.msRequestFullscreen();
        }
      }
    } catch (fallbackError) {
      console.error('备选全屏方法也失败:', fallbackError);
    }
  }
}

// 处理ESC键退出自定义全屏
const handleEscKeyExit = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    // 查找所有标记为全屏的容器
    isFullScreenStatus.value = false
    const fullscreenContainers = document.querySelectorAll('[data-fullscreen="true"]');
    fullscreenContainers.forEach(container => {
      exitCustomFullscreen(container as HTMLElement);
    });
  }
}

// 退出自定义全屏模式
const exitCustomFullscreen = (element: HTMLElement) => {
  try {
    // 获取原始样式
    const originalStylesStr = element.getAttribute('data-original-styles');
    if (originalStylesStr) {
      const originalStyles = JSON.parse(originalStylesStr);

      // 恢复原始样式
      element.style.position = originalStyles.position || '';
      element.style.width = originalStyles.width || '';
      element.style.height = originalStyles.height || '';
      element.style.top = originalStyles.top || '';
      element.style.left = originalStyles.left || '';
      element.style.zIndex = originalStyles.zIndex || '';

      // 移除标记
      element.removeAttribute('data-fullscreen');
      element.removeAttribute('data-original-styles');
    }
  } catch (error) {
    console.error('恢复原始样式失败:', error);
    // 出错时直接重置样式
    element.style.position = '';
    element.style.width = '';
    element.style.height = '';
    element.style.top = '';
    element.style.left = '';
    element.style.zIndex = '';
    element.removeAttribute('data-fullscreen');
  }
}

// 开始轮播
const startRotation = () => {
  const totalCameras = filteredCamerasList.value.length
  if (totalCameras <= ITEM_PAGE_CAMERAS.value) return;

  // 清除之前的定时器
  if (rotationTimer) {
    clearInterval(rotationTimer);
  }

  // 不需要定时刷新
  // rotationTimer = setInterval(() => {
  //   const totalPages = Math.ceil(totalCameras / ITEM_PAGE_CAMERAS.value);
  //   const nextPage = (currentPage.value + 1) % totalPages;
  //   console.log(nextPage, '==nextPage==')
  //   switchToPage(nextPage);
  // }, ROTATION_INTERVAL);
}

// 切换到上一页
const goPrevPage = () => {
  const totalCameras = filteredCamerasList.value.length;
  const totalPages = Math.ceil(totalCameras / ITEM_PAGE_CAMERAS.value);
  if (totalPages <= 1) return;

  const prevPage = (currentPage.value - 1 + totalPages) % totalPages;
  switchToPage(prevPage);

  // 重启轮播定时器，保证用户有足够的时间查看当前页面
  if (totalCameras > ITEM_PAGE_CAMERAS.value) {
    // 重新开始计时
    startRotation();
  }
}

// 切换到下一页
const goNextPage = () => {
  const totalCameras = filteredCamerasList.value.length;
  const totalPages = Math.ceil(totalCameras / ITEM_PAGE_CAMERAS.value);
  if (totalPages <= 1) return;

  const nextPage = (currentPage.value + 1) % totalPages;
  switchToPage(nextPage);

  // 重启轮播定时器，保证用户有足够的时间查看当前页面
  if (totalCameras > ITEM_PAGE_CAMERAS.value) {
    // 重新开始计时
    startRotation();
  }
}

// 初始化数据
const initData = async () => {
  // 先获取token
  await fetchEzvizToken()
  await fetchCheckList()
  // 再获取监控点列表，但不立即初始化播放器
  return await fetchChannelList()
}

// 切换视频模式
const changeVideoMode = (mode: VideoMode) => {
  if (mode === currentMode.value) return;

  // 更新显示模式
  currentMode.value = mode;

  // 停止所有播放器
  stopAllPlayers();

  // 重置页码
  currentPage.value = 0;

  // 计算页面显示的监控点范围
  const totalCameras = filteredCamerasList.value.length;
  const startIndex = 0;
  const endIndex = Math.min(startIndex + ITEM_PAGE_CAMERAS.value, totalCameras);

  // 更新视频网格
  videoGrids.value = filteredCamerasList.value.slice(startIndex, endIndex);

  // 使用nextTick确保DOM已更新后再初始化播放器
  nextTick(() => {
    // 延迟一点时间确保DOM已完全渲染
    setTimeout(() => {
      console.log(`切换视频模式为${mode}，初始化播放器`);

      // 确保DOM容器尺寸已调整
      const videoGridContainer = document.querySelector(mode === 1 ? '.single-video-container' : '.video-grid');
      if (videoGridContainer) {
        // 强制触发重绘
        videoGridContainer.classList.add('size-change');
        setTimeout(() => {
          videoGridContainer.classList.remove('size-change');
          // 此时布局已完成，计算尺寸并初始化播放器
          initCurrentPagePlayers();
        }, 50);
      } else {
        // 如果容器不存在，也尝试初始化播放器
        initCurrentPagePlayers();
      }

      // 如果有多个可轮播的页面，重新启动轮播
      if (filteredCamerasList.value.length > ITEM_PAGE_CAMERAS.value) {
        startRotation();
      }
    }, 200);
  });
}

// 视频网格的布局样式，基于当前模式
const gridStyle = computed(() => {
  switch (currentMode.value) {
    case 1:
      return {
        gridTemplateColumns: 'repeat(1, 1fr)',
        gridTemplateRows: 'repeat(1, 1fr)'
      };
    case 2:
      return {
        gridTemplateColumns: 'repeat(1, 1fr)',
        gridTemplateRows: 'repeat(2, 1fr)'
      };
    case 4:
      return {
        gridTemplateColumns: 'repeat(2, 1fr)',
        gridTemplateRows: 'repeat(2, 1fr)'
      };
    case 9:
    default:
      return {
        gridTemplateColumns: 'repeat(3, 1fr)',
        gridTemplateRows: 'repeat(3, 1fr)'
      };
  }
});

// 计算播放器尺寸，基于当前模式
const playerSize = computed(() => {
  // 获取容器尺寸
  const container = document.querySelector('.video-wrapper');
  let containerWidth = 900;  // 默认宽度
  let containerHeight = 600; // 默认高度

  if (container) {
    // 考虑padding (36px 12px 12px 12px)
    containerWidth = container.clientWidth - 24; // 左右各12px的padding
    containerHeight = container.clientHeight - 48; // 上36px下12px的padding
  }

  // 根据当前模式计算每个播放器的尺寸
  switch (currentMode.value) {
    case 1:
      return {
        width: containerWidth,
        height: containerHeight
      };
    case 2:
      // 2分屏上下布局，考虑grid的间隔(gap: 10px)
      return {
        width: containerWidth,
        height: (containerHeight - 10) / 2
      };
    case 4:
      // 考虑grid的间隔(gap: 10px)
      return {
        width: (containerWidth - 10) / 2,
        height: (containerHeight - 10) / 2
      };
    case 9:
      // 考虑grid的间隔(gap: 10px)
      return {
        width: (containerWidth - 20) / 3,  // 两个水平间隔
        height: (containerHeight - 20) / 3  // 两个垂直间隔
      };
    default:
      return {
        width: 600,
        height: 400
      };
  }
});

// 监听窗口大小变化以更新播放器尺寸
const updatePlayerSizeOnResize = () => {
  if (allCameras.value.length === 0) return;

  const size = playerSize.value;

  // 更新所有当前播放的视频尺寸
  videoGrids.value.forEach(camera => {
    if (camera.player) {
      try {
        camera.player.resize(size.width, size.height);
      } catch (error) {
        console.error('调整播放器尺寸失败:', error);
      }
    }
  });
};

// 添加窗口大小变化监听
onMounted(() => {
  //处理视频列表
  handlerVideoList()
  window.addEventListener('resize', updatePlayerSizeOnResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', updatePlayerSizeOnResize);
  document.removeEventListener('keydown', handleEscKeyExit);
  if (rotationTimer) {
    clearInterval(rotationTimer);
  }
  stopAllPlayers();
})

// 处理传感器数据
const processSensorData = (data: any) => {
  try {
    // 根据 MN 获取对应的监控点列表
    const channel = allCameras.value.find(item => item.SensorDeviceMN === data.MN)
    if (!channel) {
      return
    }
    let list = getSensorData(data)
    // 判空处理
    if (!list || !Array.isArray(list) || list.length === 0) {
      return
    }
    // 构建 Map：以 key 为键，确保新数据会覆盖旧数据
    const sensorMap = new Map()
    // 先加入旧数据
    channel.SensorData?.forEach(item => {
      sensorMap.set(item.key, item)
    })
    // 再加入新数据，相同 key 会自动覆盖，但是需要注意：如果新数据的值为空，则不会覆盖旧数据
    list.forEach(item => {
      if (item.value) {
        sensorMap.set(item.key, item)
      }
    })
    // 转换回数组
    channel.SensorData = Array.from(sensorMap.values())
    // 打印调试
  } catch (error) {
    console.error('处理传感器数据错误:', error)
  }
}

const handlerVideoList = async () => {
  if (typeof EZUIKit !== 'undefined') {
    // 初始化数据，但暂不初始化播放器
    const hasChannels = await initData()

    // 确保DOM已渲染且有数据后再初始化播放器
    if (hasChannels) {
      nextTick(() => {
        console.log('DOM已渲染，初始化播放器');

        // 确保容器已经渲染并可测量
        setTimeout(() => {
          // 使用延时确保DOM完全渲染
          const containerSelector = currentMode.value === 1 ? '.single-video-container' : '.video-grid';
          const container = document.querySelector(containerSelector);

          if (container) {
            // 触发布局更新
            container.classList.add('size-change');
            setTimeout(() => {
              container.classList.remove('size-change');
              // 初始化当前页面的播放器
              initCurrentPagePlayers();

              // 启动轮播
              if (filteredCamerasList.value.length > ITEM_PAGE_CAMERAS.value) {
                startRotation();
              }
            }, 50);
          } else {
            // 如果容器不存在，也尝试初始化播放器
            initCurrentPagePlayers();

            // 启动轮播
            if (filteredCamerasList.value.length > ITEM_PAGE_CAMERAS.value) {
              startRotation();
            }
          }
        }, 500);
      });
    }
  } else {
    console.error('萤石云SDK未加载，请确保已引入相关脚本');
    videoGrids.value.forEach(item => {
      item.loading = false;
      item.error = true;
    });
  }
}

// 处理传感器数据的方法
const getSensorData = (data: any) => {
  // 获取相关的传感器配置列表
  const relatedConfigs = props.videoEleList.filter(config => config.ItemVisible)

  if (relatedConfigs.length === 0) return []

  // 结果数组
  const result: { label: string, value: string | number, key: string }[] = []

  // 遍历配置项
  for (const config of relatedConfigs) {

    // 获取显示项列表 多选
    const visibleList = config.VisibleList.split(';')

    // 遍历显示项
    for (const listItem of visibleList) {
      // 获取对应的值键名
      const valueKey = `${config.ItemValue}-${visibleListMap[listItem]}`

      const key = `${config.ItemName}`

      // 检查数据是否存在
      if (data.CP) {
        result.push({
          label: `${config.ItemName}${listItem}`,
          value: data.CP[valueKey],
          key
        })
      }
    }
  }

  return result
}
</script>

<template>
  <div class="video-wrapper">
    <div class="video-controls">
      <div class="mode-switcher">
        <div class="mode-button" :class="{ active: currentMode === 1 }" @click="changeVideoMode(1)">
          1分屏
        </div>
        <div class="mode-button" :class="{ active: currentMode === 2 }" @click="changeVideoMode(2)">
          2分屏
        </div>
        <div class="mode-button" :class="{ active: currentMode === 4 }" @click="changeVideoMode(4)">
          4分屏
        </div>
        <div v-if="powerCode === 'admin'" class="mode-button" :class="{ active: currentMode === 9 }" @click="changeVideoMode(9)">
          9分屏
        </div>
      </div>
      <div class="pagination-controls">
        <div class="page-arrow" @click="goPrevPage">
          <span>◀</span>
        </div>
        <div class="page-indicator">
          {{ currentPage + 1 }}/{{ Math.ceil(filteredCamerasList.length / ITEM_PAGE_CAMERAS) }}
        </div>
        <div class="page-arrow" @click="goNextPage">
          <span>▶</span>
        </div>
      </div>
    </div>

    <div v-if="listLoading" class="empty-grid">
      加载中...
    </div>
    <div v-else style="height: 100%;">
      <!-- 1分屏模式显示 -->
      <div v-if="currentMode === 1" class="single-video-container">
        <VideoItem v-if="videoGrids.length > 0" :item="videoGrids[0]" :index="0" @double-click="handleDoubleClick" />
      </div>

      <!-- 2分屏模式显示 -->
      <div v-else-if="currentMode === 2" class="video-grid" :style="gridStyle">
        <VideoItem v-if="videoGrids.length > 0" :item="videoGrids[0]" :index="0" @double-click="handleDoubleClick" />
        <VideoItem v-if="videoGrids.length > 1" :item="videoGrids[1]" :index="1" @double-click="handleDoubleClick" />
      </div>

      <!-- 4分屏和9分屏模式显示 -->
      <div v-else class="video-grid">
        <div v-if="videoGrids.length === 0" class="empty-grid">
          未添加主监控点，请先添加
        </div>
        <div v-else class="video-grid" :style="gridStyle">
          <VideoItem v-for="(item, index) in videoGrids" :key="index" :item="item" :index="index"
            @double-click="handleDoubleClick" />
        </div>
      </div>
    </div>

    <div v-if="isFullScreenStatus" class="video-full-screen-element">
      <SensorData v-if="fullInfo.SensorData" :sensorData="fullInfo.SensorData" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.video-wrapper {
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 36px 12px 12px 12px;
  box-sizing: border-box;
  position: relative;
  z-index: 15;
}

.video-controls {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 8px;
  position: absolute;
  top: 6px;
  right: 12px;
  z-index: 1000;
}

.mode-switcher {
  display: flex;
  margin-right: 12px;
}

.mode-button {
  background-color: rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #999;
  padding: 3px 8px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  margin-right: 4px;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background-color: rgba(0, 0, 0, 0.7);
    color: #ddd;
  }

  &.active {
    border: 1px solid rgba(255, 255, 255, 0.65);
    color: #fff;
  }
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.page-arrow {
  color: #fff;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 3px;
  padding: 2px 8px;
  cursor: pointer;
  user-select: none;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;

  &:hover {
    background-color: rgba(0, 0, 0, 0.7);
  }
}

.page-indicator {
  color: #fff;
  padding: 2px 12px;
  font-size: 14px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 3px;
  margin: 0 5px;
}

/* 1分屏视频容器样式 */
.single-video-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(1, 1fr);
  grid-template-rows: repeat(1, 1fr);
}

.video-grid {
  display: grid;
  gap: 10px;
  width: 100%;
  height: 100%;
  transition: all 0.3s;

  &.size-change {
    opacity: 0.8;
    transform: scale(0.98);
  }
}

.video-full-screen-element {
  position: fixed;
  top: 10px;
  right: 25px;
  z-index: 100000000;
}

.empty-grid {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #ffffff;
}
</style>